/*
 * @Author: YiY
 * @Date: 2023-12-13 19:51:51
 * @LastEditTime: 2024-12-11 19:21:09
 */
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
// import localCache from '@/utils/cache';
import { ElMessage } from "element-plus";
import { DefineComponent } from "vue";
import { c } from "node_modules/vite/dist/node/types.d-aGj9QkWt";
// import { DefineComponent } from 'vue';

type RouteMetaType = {
  title: string;
  order: number;
  parentId: number | null;
};
let routeMeta: Record<string, RouteMetaType> = import.meta.glob(
  "../views/**/*.ts",
  {
    eager: true,
    import: "default",
  }
);

// @ts-ignore
const routeComponent: Record<
  string,
  () => Promise<DefineComponent<{}, {}, any>>
> = import.meta.glob("../views/**/*.vue");

// const routeComponent: Record<string, any> = import.meta.glob('../views/**/*.vue');

console.log("routeComponent :>> ", routeComponent);

export const genRoutes = Object.entries(routeMeta).map(([path, meta], idx) => {
  path = path.replace("../views", "").replace("/page.ts", "") || "/";
  let name = path.replace("/", "");

  let componentList =  Object.entries(routeComponent).filter((item) => {
    // console.log("item :>> ", item);
    const reg = /\/(\w+)\/(\w+)\.vue$/
    console.log('item[0] :>> ', item[0]);
    let match = item[0].match(reg)
    // TODO
    if(match![1] === match![2] ){
      console.log('reg :>> ', match![2]);
      return item
    }
    
  });
  console.log("componentList :>> ", componentList);

  const component = componentList[idx][1];

  let routeObj = {
    path,
    name,
    meta,
    component,
  };

  if (meta.parentId) {
    routeObj.meta.parentId = meta.parentId;
  }

  return routeObj;
});

console.log("genRoutes :>> ", genRoutes);

const routes: Array<RouteRecordRaw> = [
  {
    // 路由初始指向
    path: "/",
    redirect: "/home",
  },
  ...genRoutes,
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  if (to.name == "login") {
    // localCache.clearCache()
    return next();
  }

  // 路由 不存在
  let arrPath = routes.map((item) => item.path);
  if (!arrPath.includes(to.path)) {
    ElMessage({ message: "路由不存在~", type: "warning" });
    router.push("/");
  }

  // let token = localCache.getCache("token")
  // if(!token) router.replace('/login');

  next();
});
export default router;
